package com.sdksoft.readcard

import android.app.PendingIntent
import android.content.Intent
import android.graphics.Bitmap
import android.media.MediaPlayer
import android.nfc.NfcAdapter
import android.os.Build
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.view.View
import android.widget.LinearLayout
import com.csht.bean.IdCardData
import com.csht.enums.StatusCode
import com.csht.listener.ReadCardListener
import com.sdksoft.readcard.databinding.IdcardPhotoBinding
import com.sdksoft.readcard.databinding.IdcardShowlogBinding
import com.sdksoft.readcard.databinding.IdcardViewBinding
import com.sdksoft.readcard.utils.dp2px
import com.csht.utils.BytesUtils
import com.csht.utils.HHTipUtils
import com.csht.utils.LogUtils
import com.csht.utils.NfcUtils
import java.io.FileOutputStream
import java.text.DecimalFormat
import kotlin.math.max

open class BaseIDCardActivity : BaseInitActivity(), ReadCardListener {

    private var player: MediaPlayer? = null

    protected val mHandler: Handler = Handler(Looper.getMainLooper())

    //1.声明一个nfc的Adapter
    private lateinit var nfcUtils: NfcUtils

    protected lateinit var idcardViewBinding: IdcardViewBinding
    protected lateinit var idcardShowlogBinding: IdcardShowlogBinding
    protected lateinit var idcardPhotoBinding: IdcardPhotoBinding

    private var successTime = 0
    private var readTime = 0
    private var alltime: Long = 0
    private var smallTime: Long = 1500

    private var logLine = 0

    override fun initView() {
        super.initView()
        idcardViewBinding = IdcardViewBinding.inflate(layoutInflater)
        idcardShowlogBinding = IdcardShowlogBinding.inflate(layoutInflater)
        idcardPhotoBinding = IdcardPhotoBinding.inflate(layoutInflater)
        baseActivityBinding.llContent.apply {
            addView(idcardViewBinding.root, 0)
            addView(idcardShowlogBinding.root, 1)
            val layoutParams =
                LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, dp2px(200))
            idcardShowlogBinding.logScroll.layoutParams = layoutParams
            idcardShowlogBinding.tvLog.setOnLongClickListener {
                idcardShowlogBinding.tvLog.text = ""
                true
            }
        }
        nfcUtils = NfcUtils(this, this.javaClass)
        player = MediaPlayer.create(applicationContext, R.raw.success)
    }

    fun appendLog(log: String) {
        logLine++
        if (logLine > 100) {
            logLine = 0
            idcardShowlogBinding.tvLog.text = ""
        }
        idcardShowlogBinding.apply {
            tvLog.append(log)
            mHandler.postDelayed({ logScroll.fullScroll(View.FOCUS_DOWN) }, 200)
        }
    }

    override fun onStart() {
        super.onStart()
        Log.d("readcard", "onStart")
        nfcUtils.nfcInit(this,  this.javaClass)
    }

    override fun onResume() {
        super.onResume()
        Log.d("readcard", "onResume")
        //设置处理优于所有其他NFC的处理
        nfcUtils.onResume( this)
    }

    override fun onPause() {
        super.onPause()
        Log.d("readcard", "onPause")
        //恢复默认状态
        nfcUtils.onPause( this)
    }

    override fun onReadCardState(type: Int, msg: String) {
        if (type == StatusCode.READCARD_FAILE.code) {
//            HHTipUtils.getInstance().dismissProgressDialog()
//            HHTipUtils.getInstance().showToast(this, "type:$type\n$msg")
            showTJ(false)
        }
//        else if (type == StatusCode.READCARD_SUCCESS.code) {
//            HHTipUtils.getInstance().dismissProgressDialog()
//            HHTipUtils.getInstance().showToast(this, "type:$type\n$msg")
//        } else if (type == StatusCode.FIND_CARD_SUCCESS.code) {
//            if (!HHTipUtils.getInstance().progressDialogIsShowing()) {
//                HHTipUtils.getInstance().showProgressDialog(this, "正在读取,请勿移动")
//            }
//        }
        appendLog("\n----------------------------\nstatus: $type  ，msg:$msg")
//        if (msg.contains("超时")) {
//            readCardManager.readCardStop()
//            readCardManager.readCardReleaseDestory()
//            HHTipUtils.getInstance().dismissProgressDialog()
//        }
    }

    override fun onReadICCardSuccess(icnumber: String, type: Int) {
        player?.start()
        val typeName = when (type) {
            StatusCode.CARD_IC.code -> StatusCode.CARD_IC.msg
            StatusCode.CARD_M1.code -> StatusCode.CARD_M1.msg
            StatusCode.CARD_LCT_STUDENT.code -> StatusCode.CARD_LCT_STUDENT.msg
            StatusCode.CARD_LCT_NORMAL.code -> StatusCode.CARD_LCT_NORMAL.msg
            StatusCode.CARD_LCT_OLD.code -> StatusCode.CARD_LCT_OLD.msg
            StatusCode.CARD_SB.code -> StatusCode.CARD_SB.msg
            StatusCode.CARD_BANK.code -> StatusCode.CARD_BANK.msg
            else -> type.toString()
        }
        appendLog("\n----------------------------\ntype: $typeName\nicNumber:$icnumber")
    }

    override fun onReadIDCardSuccess(bean: IdCardData) {
        player?.start()
        idcardViewBinding.apply {
            bean.apply {
                imgMan.setImageBitmap(bitmap)
                txtSex.text = bean.sex
                txtPolice.text = bean.issue
                txtCardID.text = bean.id
                txtValid.text = "${bean.startDate}-${bean.endDate}"
                if (bean.type == StatusCode.CARD_IDCARD_FOREIGN.code || bean.type == StatusCode.CARD_IDCARD_FOREIGN_OLD.code) { // 外国居住证
                    txtName.text = bean.nameChinese + bean.nameEnglish
                    txtNation.text = bean.nationlity
                } else if (bean.type == StatusCode.CARD_IDCARD.code || bean.type == StatusCode.CARD_IDCARD_GAT.code) {
                    txtName.text = bean.name
                    txtNation.text = bean.nation
                    txtAddress.text = bean.address
                }
                try {
                    txtY.text = bean.birthday.substring(0, 4)
                    txtM.text = bean.birthday.substring(4, 6)
                    txtD.text = bean.birthday.substring(6, 8)
                } catch (e: java.lang.Exception) {
                }
                if (fingerPrint.isNotEmpty()) {
                    // fingerPrint写入文件
                    val fingerPrintFile =
                        getExternalFilesDir(null)!!.absolutePath + "/2.fp"
                    val fileOutputStream = FileOutputStream(fingerPrintFile)
                    if (fingerPrint.size >= 512) {
                        fileOutputStream.write(fingerPrint.copyOfRange(0, 512))
                    } else {
                        fileOutputStream.write(fingerPrint)
                    }
                    fileOutputStream.close()
                    Log.e("------指纹----", BytesUtils.bytesToHexString(fingerPrint))
                }
            }
            showTJ(true, bean)
        }
    }

    override fun onReadIDCardPhoto(frontPhoto: Bitmap?, backPhoto: Bitmap?) {
        super.onReadIDCardPhoto(frontPhoto, backPhoto)
        baseActivityBinding.llContent.apply {
            removeView(idcardPhotoBinding.root)
            if (frontPhoto != null && backPhoto != null) {
                addView(idcardPhotoBinding.root)
                idcardPhotoBinding.apply {
                    idcardPhotoFront.setImageBitmap(frontPhoto)
                    idcardPhotoBack.setImageBitmap(backPhoto)
                    try {
                        val front = getExternalFilesDir(null)!!.absolutePath + "/front.png"
                        val fileOutputStream = FileOutputStream(front)
                        frontPhoto.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream)
                        fileOutputStream.close()

                        val back = getExternalFilesDir(null)!!.absolutePath + "/back.png"
                        val backOutputStream = FileOutputStream(back)
                        backPhoto.compress(Bitmap.CompressFormat.PNG, 100, backOutputStream)
                        backOutputStream.close()
                    } catch (e: Exception) {
                    }
                }
            }
        }
    }

    override fun onAsynResult(isSuccess: Boolean, msg: String?, requestId: String?) {
        super.onAsynResult(isSuccess, msg, requestId)
        player?.start()
        appendLog("\n----------------------------\n异步结果: $isSuccess\nmsg:$msg\nrequestId:$requestId")
    }

    override fun onResultM1Data(data: ByteArray?) {
        super.onResultM1Data(data)
        HHTipUtils.getInstance().dismissProgressDialog()
        data?.let {
            appendLog("\n----------------------------\nM1卡: \n${BytesUtils.bytesToHexString(it)}")
        }
    }

    fun clear() {
        idcardViewBinding.apply {
            txtName.text = ""
            txtSex.text = ""
            txtNation.text = ""
            txtPolice.text = ""
            txtCardID.text = ""
            txtValid.text = ""
            txtY.text = ""
            txtM.text = ""
            txtD.text = ""
            txtAddress.text = ""
            imgMan.setImageDrawable(resources.getDrawable(R.mipmap.ic_launcher))
        }
    }

    fun showTJ(isSuccess: Boolean, bean: IdCardData? = null){
        var distime = 0L
        if (isSuccess) {
            bean?.let {
                successTime++
                readTime++
                alltime += bean.distime
                if (bean.distime < smallTime) {
                    smallTime = bean.distime
                }
                distime = bean.distime
            }
        } else {
            readTime++
        }
        appendLog("\n----------------------------\n")
        val log = "解码次数" + readTime + "  解码成功次数" + max(0, successTime) + "  解码时间：" + distime + "ms  \n" +
                "成功率:" + keepTwoDecimalPlaces(max(0, successTime) * 100.0 / max(1, readTime)) + "%   平均耗时：" + keepTwoDecimalPlaces(
            (alltime / max(1, successTime)).toDouble()
        ) + "ms   最小耗时：" + smallTime + "ms\n"
        appendLog(log)
        LogUtils.i(log)
    }

    fun keepTwoDecimalPlaces(value: Double): String {
        try {
            val df = DecimalFormat("#0.00")
            return df.format(value)
        } catch (e: Exception) {
        }
        return value.toString()
    }

    override fun onDestroy() {
        super.onDestroy()
        mHandler.removeCallbacksAndMessages( null)
        mainHandler.removeCallbacksAndMessages(null)
        player?.release()
        readCardManager.readCardStop()
        readCardManager.readCardReleaseDestory()
    }
}